package com.zcy;

import com.espertech.esper.common.client.EventBean;
import com.espertech.esper.runtime.client.EPEventService;
import com.zcy.event.MyEvent;
import com.zcy.util.EsperBuilder;
import com.zcy.util.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * 14.3.2. Length Batch Window (length_batch or win:length_batch)
 * 称为滚动窗口（Tumbling Window)
 */
@Slf4j
public class LengthBatchWindow extends TimeUtils {

    private static final String _LengthBatch = "@name('length-batch') select sum(num) from MyEvent#length_batch(3)";

    /**
     * length_batch
     * sum is : 60
     * 缺点：
     *  1. 滚动窗口相较于滑动窗口显得不那么平滑
     *  2. 若最后一个滚动窗口因窗口条件不满足则会永久不被触发计算，导致数据遗漏
     */
    @Test
    public void lengthWindowTest() {
        EsperBuilder esperBuilder = new EsperBuilder(_LengthBatch, new Class[]{MyEvent.class});

        esperBuilder.startCompile();

        EPEventService epEventService = esperBuilder.startDeploy((eventBeans, eventBeans1, epStatement, epRuntime) -> Stream.of(eventBeans).forEach(item -> {
            for (int i = 0; i < eventBeans.length; i++) {
                EventBean eventBean = eventBeans[i];
                log.info("sum is : {}", eventBean.get("sum(num)"));
            }
        }));

        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("001").name("001-name").num(10).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.SECONDS, 2L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(20).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.SECONDS, 3L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("003").name("003-name").num(30).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.SECONDS, 4L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("004").name("004-name").num(40).build(), MyEvent.class.getSimpleName());

        sleep(TimeUnit.SECONDS, 40L);
    }



}
